import sys
import pygame
import dynamics2D
from decimal import Decimal
from threading import Thread

def sqrt(x):
    D = Decimal(x)
    return Decimal.sqrt(D)

width, height = 1600,900
center = width/2, height/2
ratio = 3

color = [
    pygame.Color(255,0,0,255),
    pygame.Color(0,255,0,255),
    pygame.Color(0,0,255,255),
    pygame.Color(255,255,0,200),
    pygame.Color(0,255,0,10),
    pygame.Color(0,0,255,10),
    pygame.Color(255,255,255,255),
    pygame.Color(255,255,255,0),
    pygame.Color(0,0,0,255),
    pygame.Color(0,0,0,0),
    pygame.Color(0,0,0,0)
]

pygame.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode((width,height),pygame.SRCALPHA)
screen.fill(color[8])


mp_surface = pygame.Surface((width, height),pygame.SRCALPHA).convert_alpha()
trace_surface = pygame.Surface((width, height),pygame.SRCALPHA).convert_alpha()
trace_surface_mask = pygame.Surface((width, height),pygame.SRCALPHA).convert_alpha()
trace_surface.fill(color[7])
screen.blit(trace_surface,(0,0))
screen.blit(mp_surface,(0,0))

system1 = [
    [4,(0,0),(0,0)],
    [4,(50,0),(0,100)],
    [4,(-50,0),(0,-100)]
]

v2 = sqrt(7000)
system2 = [
    [4,(0,-50),         (-v2,0)],
    [4,(-25*sqrt(3),25), (v2/2,v2/2*sqrt(3))],
    [4,(25*sqrt(3),25),(v2/2,-v2/2*sqrt(3))]
]

system3 = [
    [4,(100,0),(0,35)],
    [4,(-100,0),(0,-35)],
    [0.01,(200,0),(20,-24)]
]

system4 = [
    [4,(100,-50),(0,48)],
    [4,(-140,120),(-15,-36)],
    [2,(120.6,100),(30,-24)]
]

system5 = [
    [4,(100,-50),(0,48)],
    [4,(-140,120),(-15,-36)],
    [2,(120.6,100),(30,-24)],
    [0.001,(140,-80),(-70,-94)]
]

world = dynamics2D.World(system5)
size = world.mp_num
world.run()

pos = world.pos
last_pos = world.pos

while True:
    pass
    screen.fill(color[8])
    # 循环获取事件，监听事件状态
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            world.stop()
            sys.exit()
    
    pos = world.pos
    mp_surface.fill(color[10])

    trace_surface_mask.fill(color[9])
    dim_mask = pygame.Rect(0,0,width,height)
    for i in range(size):
        x = pos[i]
        x0 = last_pos[i]
        pygame.draw.circle(mp_surface,color[i],(center[0]+float(x[0])/ratio,center[1]+float(x[1])/ratio),5)
        pygame.draw.line(trace_surface_mask, color[i],
            (center[0]+float(x0[0])/ratio,center[1]+float(x0[1])/ratio),
            (center[0]+float( x[0])/ratio,center[1]+float( x[1])/ratio), 1)
    last_pos = pos
    trace_surface.blit(trace_surface_mask,(0,0))
    screen.blit(trace_surface,(0,0))
    screen.blit(mp_surface,(0,0))
    pygame.display.set_caption(f'FPS:{clock.get_fps()} Time:{world.time}')
    clock.tick(600)
    #screen2.blit(mp_surface,(0,0))
    pygame.display.update() #更新屏幕内容